package br.com.caiocarrara.goodbuy.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.Component;
import br.com.caiocarrara.goodbuy.model.Product;

@Component
public class ProductDao {

	private final Session session;

	public ProductDao(Session session) {
		this.session = session;
	}

	public void save(Product product) {
		Transaction tx = this.session.beginTransaction();
		this.session.save(product);
		tx.commit();
	}

	public void update(Product product) {
		Transaction tx = this.session.beginTransaction();
		this.session.update(product);
		tx.commit();
	}

	public void delete(Product product) {
		Transaction tx = this.session.beginTransaction();
		this.session.delete(product);
		tx.commit();
	}

	public Product getById(Long id) {
		Product product = (Product) this.session.load(Product.class, id);
		return product;
	}

	@SuppressWarnings("unchecked")
	public List<Product> listAll() {
		return this.session.createCriteria(Product.class).list();
	}

	@SuppressWarnings("unchecked")
	public List<Product> search(String name) {
		return session.createCriteria(Product.class)
				.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE))
				.list();
	}

	public void reload(Product product) {
		this.session.refresh(product);
	}
}
